<?php

namespace app\index\controller;

use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Validate;

class Api extends Controller
{
    /**
     * 获取openid
     */
    public function getOpenid()
    {
        $input = Request()->param();
        
        $code = $input['code'];
        
        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');
        
        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        
        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        
        $user_data = json_decode(file_get_contents($url));
        
        apiReturn(1, '获取数据成功', $user_data);
    }
    
    public function getConfig()
    {
        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        
        $data = [
            'appid' => $appid,
            'secret' => $secret
        ];
        
        apiReturn(1, '获取数据成功', $data);
    }
    
    /**
     * 微信登录
     * */
    public function wxLogin()
    {
        $input = Request()->param();
        
        $code = $input['code'];
        $encryptedData = $input['encryptedData'];
        $iv = $input['iv'];
        
        if (empty($encryptedData)) apiReturn(2, 'encryptedData不能为空');
        if (empty($iv)) apiReturn(2, 'iv不能为空');
        
        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';
        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $user_data = json_decode(file_get_contents($url));
        
        $session_key = $user_data->session_key;
        
        $data = "";
        Loader::import('wxLogin\wxBizDataCrypt', EXTEND_PATH);
        $obj = new \WXBizDataCrypt($appid, $session_key);
        $errCode = $obj->decryptData($encryptedData, $iv, $data);
        
        if ($errCode == 0) {
            $data = json_decode($data, true);
            
            $username = $data['nickName'];
            $avatar = $data['avatarUrl'];
            $openid = $user_data->openid;
            
            $save_data = [
                'username' => $username,
                'avatar' => $avatar,
                'openid' => $openid
            ];
            $data = bindUser($save_data);
            
            if ($data) {
                apiReturn(1, '登录成功', $data);
            } else {
                apiReturn(2, '登录失败');
            }
        } else {
            file_put_contents(RUNTIME_PATH . 'login_error.log', 'code：' . $code . '；encryptedData：' . $encryptedData . '；iv：' . $iv . '；errCode' . $errCode . PHP_EOL);
            
            apiReturn(2, '登录失败，错误码：' . $errCode);
        }
    }
    
    /**
     * 首页banner
     * */
    public function indexBanner()
    {
        $banner_list = Db::name('banner')->field('id,img,type,to_id')->select();
        
        if ($banner_list) {
            foreach ($banner_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $banner_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * banner文章详情
     * */
    public function bannerArticleDetail()
    {
        $input = Request()->param();
        
        $id = $input['id'];
        
        if (empty($id)) apiReturn(2, '文章ID缺失');
        
        $info = Db::name('article')->field('id,title,content,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time']);
            
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在或已删除');
        }
    }
    
    /**
     * 商品分类
     * */
    public function goodsTypeList()
    {
        $list = Db::name('goods_type')->field('id,name')->where(['pid' => 0])->order('sort asc')->select();
        
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 商品品牌
     * */
    public function goodsBrandList()
    {
        $list = Db::name('goods_brand')->field('id,name')->order('sort asc')->select();
        
        if ($list) {
            apiReturn(1, '获取数据成', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $name = $input['name'];
        $one_type_id = $input['one_type_id'] ?: 0;
        $brand_id = $input['brand_id'] ?: 0;
        $sort = $input['sort'] ?: 0;//0：综合，1：销量，2：价格升序，3：价格升序
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        $where['upper'] = 1;
        
        if ($name) $where['name'] = ['LIKE', '%' . $name . '%'];
        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($brand_id) $where['brand_id'] = $brand_id;
        
        switch ($sort) {
        case 1:
            $order = 'sales_count desc';
            break;
        case 2:
            $order = 'min_price asc';
            break;
        case 3:
            $order = 'min_price desc';
            break;
        default:
            $order = 'id desc';
            break;
        }
        
        $goods_list = Db::name('goods')->field('id,img,name,min_price,sales_count')->where($where)->order($order)->page($page, $pagesize)->select();
        if ($goods_list) {
            foreach ($goods_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $goods_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 商品详情
     * */
    public function goodsDetail()
    {
        $input = Request()->param();
        
        $id = $input['id'];
        $user_id = $input['user_id'];
        
        if (empty($id)) apiReturn(2, '商品ID缺失');
        
        $info = Db::name('goods')->field('id,name,img,imgs,sales_count,min_price,content,user_instructions,product_param')->where(['id' => $id])->find();
        if ($info) {
            $info['img'] = getPicture($info['img']);
            $info['imgs'] = doImgs($info['imgs']);
            $min_market_price = Db::name('sku_value')->where(['goods_id' => $id, 'status' => 1])->min('market_price');
            $info['min_market_price'] = sprintf('%.2f', $min_market_price);
            $info['content'] = doEditorContent($info['content']);
            $info['product_param'] = json_decode($info['product_param'], true);
            
            if ($user_id) {
                $collect_count = Db::name('collect')->where(['to_id' => $id, 'user_id' => $user_id, 'status' => 1])->count();
                $info['collect_status'] = $collect_count ? true : false;
            } else {
                $info['collect_status'] = false;
            }
            
            $sku_data = getSku($id);
            
            $info['sku_list'] = $sku_data['sku_list'];
            $info['sku_value_list'] = $sku_data['sku_value_list'];
            
            $comment_count = Db::name('goods_comment')->where(['goods_id' => $id])->count();
            $info['comment_count'] = $comment_count;
            
            //评价列表
            $comment_list = Db::name('goods_comment c')
                ->join('tp_user u', 'c.user_id = u.id', 'left')
                ->field('c.id,u.avatar,u.username,c.star,c.content,c.imgs,c.create_time')
                ->where(['c.goods_id' => $id])
                ->order('c.create_time desc')
                ->limit(2)
                ->select();
            if ($comment_list) {
                foreach ($comment_list as &$v) {
                    $v['avatar'] = doAvatar($v['avatar']);
                    $v['imgs'] = doImgs($v['imgs']);
                    $v['star'] = intval($v['star']);
                    $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
                }
            } else {
                $comment_list = [];
            }
            $info['comment_list'] = $comment_list;
            
            // 服务保障
            $service_guarantee = Db::name('goods_service_guarantee')->value('service_guarantee');
            $service_guarantee_arr = json_decode($service_guarantee, true);
            $info['service_guarantee'] = $service_guarantee_arr;
            $info['service_guarantee_show'] = implode('·', array_column($service_guarantee_arr, 'param'));
            
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }
    
    /**
     * 收藏/取消收藏
     * */
    public function doCollect()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $to_id = $input['to_id'];
        $type = $input['type'];    //1：商品
        $status = $input['status'];//0：取消收藏，1：收藏
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($to_id)) apiReturn(2, '收藏对象ID缺失');
        
        $time = time();
        
        $info = Db::name('collect')->where(array('user_id' => $user_id, 'to_id' => $to_id, 'type' => $type))->find();
        if ($info) {
            if ($info['status'] == $status) {
                apiReturn(2, '系统繁忙，请稍后再试~');
            } else {
                $data = array(
                    'status' => $status,
                    'update_time' => $time,
                    'create_time' => $time
                );
                $res = Db::name('collect')->where(array('id' => $info['id']))->update($data);
                $msg = $status == 0 ? '取消收藏' : '收藏';
                if ($res) {
                    apiReturn(1, $msg . '成功');
                } else {
                    apiReturn(2, $msg . '失败');
                }
            }
        } else {
            if ($status == 0) {
                apiReturn(2, '系统繁忙，请稍后再试~');
            } else {
                $data = array(
                    'user_id' => $user_id,
                    'to_id' => $to_id,
                    'type' => $type,
                    'status' => $status,
                    'create_time' => $time
                );
                $res = Db::name('collect')->insert($data);
                if ($res) {
                    apiReturn(1, '收藏成功');
                } else {
                    apiReturn(2, '收藏失败');
                }
            }
        }
    }
    
    /**
     * 商品评价列表
     * */
    public function goodsCommentList()
    {
        $input = Request()->param();
        
        $id = $input['id'];
        $page = $input['page'] ? $input['page'] : 1;
        $pagesize = $input['pagesize'] ? $input['pagesize'] : 10;
        
        if (empty($id)) apiReturn(2, '商品ID缺失');
        
        $list = Db::name('goods_comment c')
            ->join('tp_user u', 'c.user_id = u.id', 'left')
            ->field('c.id,u.avatar,u.username,c.star,c.content,c.imgs,c.create_time')
            ->where(['c.goods_id' => $id])
            ->order('c.create_time desc')
            ->page($page, $pagesize)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = doAvatar($v['avatar']);
                $v['imgs'] = doImgs($v['imgs']);
                $v['star'] = intval($v['star']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }
            
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 购物车商品数量校正
     * tips：在小程序 onHide 和 onUnload 中调用该接口
     * */
    public function doCarGoodsCount()
    {
        $input = Request()->param();
        $car_list = json_decode($input['car_list'], true);//[{"id":"4","count":"8"}]
        if ($car_list) {
            foreach ($car_list as &$v) {
                Db::name('goods_car')->where(array('id' => $v['id']))->setField('count', $v['count']);
            }
        }
    }
    
    /**
     * 加入购物车
     * */
    public function addGoodsCar()
    {
        $input = Request()->param();
        
        $id = $input['id'];//商品id
        $user_id = $input['user_id'];
        $sku_id = $input['sku_id'];//属性id组合；sku_value表sku_id
        $count = $input['count'];
        
        if (empty($id)) apiReturn(2, '商品ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if ($count <= 0) apiReturn(2, '商品数量异常');
        
        $goods_info = Db::name('goods')->where(['id' => $id])->find();
        if ($goods_info) {
            $sku_info = Db::name('sku_value')->field('sku_id,img,price,stock')->where(['sku_id' => $sku_id, 'goods_id' => $id])->find();
            if ($sku_info) {
                if ($sku_info['stock'] < $count) apiReturn(2, '商品所选属性库存不足');
                
                $car_info = Db::name('goods_car')->where(['user_id' => $user_id, 'goods_id' => $id, 'sku_id' => $sku_id])->find();
                if ($car_info) {
                    //该商品之前已经加入过购物车，这个时候只需要增加购物车数量即可
                    $res = Db::name('goods_car')->where(['id' => $car_info['id']])->setInc('count', $count);
                } else {
                    //该商品第一次加入购物车，添加购物车数据
                    $data = [
                        'user_id' => $user_id,
                        'goods_id' => $id,
                        'img' => $sku_info['img'],
                        'sku_id' => $sku_info['sku_id'],
                        'count' => $count,
                        'price' => $sku_info['price'],
                        'create_time' => time()
                    ];
                    $res = Db::name('goods_car')->insert($data);
                }
            } else {
                apiReturn(2, '属性不存在或已删除');
            }
            
            if ($res) {
                apiReturn(1, '添加成功');
            } else {
                apiReturn(2, '添加购物车失败');
            }
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }
    
    /**
     * 购物车列表
     * */
    public function goodsCarList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $list = Db::name('goods_car')->where(array('user_id' => $user_id))->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
                $goods_info = Db::name('goods')->where(['id' => $v['goods_id']])->find();
                $v['goods_name'] = $goods_info['name'];
                $v['actived'] = false;
                
                if ($sku_list = getSkuName(explode('-', $v['sku_id']))) $v['sku'] = implode('，', array_column($sku_list, 'name'));
            }
            
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }
    
    /**
     * 移除购物车商品
     * */
    public function removeGoodsCar()
    {
        $input = Request()->param();
        $car_ids = $input['car_ids'];
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        $res = Db::name('goods_car')->where(array('id' => array('IN', $car_ids)))->delete();
        if ($res) {
            apiReturn(1, '移除成功');
        } else {
            apiReturn(2, '移除失败');
        }
    }
    
    /**
     * 购物车订单确认页
     * */
    public function goodsCarOrderConfirm()
    {
        $input = Request()->param();
        $user_id = $input['user_id'];
        $car_ids = $input['car_ids'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        
        $car_list = Db::name('goods_car')->field('id,goods_id,img,sku_id,price,count')->where(array('id' => array('IN', $car_ids)))->select();
        $all_price = 0;
        if ($car_list) {
            foreach ($car_list as &$v) {
                $v['goods_name'] = Db::name('goods')->where(['id' => $v['goods_id']])->value('name');
                $v['img'] = getPicture($v['img']);
                $v['sku'] = implode('，', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));
                $all_price += sprintf("%.2f", $v['price'] * $v['count']);
            }
            //默认收货地址
            $address_info = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(array('user_id' => $user_id, 'is_default' => 1))->find();
            if ($address_info) {
                $address_info['province'] = getProvinceName($address_info['province_id']);
                $address_info['city'] = getCityName($address_info['city_id']);
                $address_info['area'] = getAreaName($address_info['area_id']);
                unset($address_info['province_id']);
                unset($address_info['city_id']);
                unset($address_info['area_id']);
            }
            
            $data = array(
                'goods_list' => $car_list,
                'all_price' => sprintf('%.2f', $all_price),
                'address' => $address_info ? $address_info : []
            );
            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '购物车商品数据异常');
        }
    }
    
    /**
     * 购物车立即支付【生成待支付订单】 之后 发起支付
     * */
    public function addGoodsCarOrder()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $car_ids = $input['car_ids'];
        $address_id = $input['address_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        if (empty($address_id)) apiReturn(2, '请选择收货地址');
        
        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');
        
        $time = time();
        
        Db::startTrans();
        try {
            $car_list = Db::name('goods_car')->field('id,goods_id,price,sku_id,count')->where(array('id' => array('IN', $car_ids)))->select();
            $all_price = 0;
            $order_res = false;
            $up_order_res = true;
            $goods_order = [];
            $order_ids = '';
            
            if ($car_list) {
                $address_info = Db::name('address')->where(array('id' => $address_id))->find();
                //支付订单号
                $pay_order_sn = 'PAY' . date('Ymd') . rand(1000, 9999) . $user_id;
                
                foreach ($car_list as $k => &$v) {
                    $goods_info = Db::name('goods')->field('id,name')->where(array('id' => $v['goods_id']))->find();
                    
                    $sku_info = Db::name('sku_value')->where(array('goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']))->find();
                    if ($sku_info) {
                        if ($v['count'] > $sku_info['stock']) apiReturn(2, $goods_info['name'] . '库存不足');
                    } else {
                        apiReturn(2, $goods_info['name'] . '属性不存在或已删除');
                    }
                    
                    $all_price += sprintf("%.2f", $v['price'] * $v['count']);
                    
                    $now_goods_price = $v['price'] * $v['count'];
                    
                    $wait_order_info = Db::name('order')->where(array('pay_order_sn' => $pay_order_sn))->find();
                    
                    if ($wait_order_info) {
                        $up_order_data = array(
                            'all_price' => $now_goods_price + $wait_order_info['all_price'],
                            'pay_price' => $now_goods_price + $wait_order_info['pay_price']
                        );
                        $up_order_res = Db::name('order')->where(array('id' => $wait_order_info['id']))->update($up_order_data);
                        
                        if (!$up_order_res) break;
                        
                        $order_res = $wait_order_info['id'];
                    } else {
                        //订单主表添加数据
                        $order_sn = 'SN' . date('Ymd') . rand(1000, 9999) . $user_id;
                        $order_data = array(
                            'user_id' => $user_id,
                            'order_sn' => $order_sn,
                            'pay_order_sn' => $pay_order_sn,
                            'all_price' => $now_goods_price,
                            'pay_price' => $now_goods_price,
                            'get_username' => $address_info['username'],
                            'get_mobile' => $address_info['mobile'],
                            'get_province' => getProvinceName($address_info['province_id']),
                            'get_city' => getCityName($address_info['city_id']),
                            'get_area' => getAreaName($address_info['area_id']),
                            'get_address' => $address_info['address'],
                            'car_ids' => $car_ids,
                            'create_time' => $time
                        );
                        $order_res = Db::name('order')->insertGetId($order_data);
                    }
                    
                    if ($order_res) {
                        //当$order_res为数值时（订单ID），走该分支
                        if ($order_ids == '') {
                            $order_ids = $order_res;
                        } else {
                            $order_ids .= ',' . $order_res;
                        }
                    }
                    
                    if (!$order_res) break;
                    
                    //准备订单副表数据
                    $goods_info = Db::name('goods')->field('id,name')->where(['id' => $v['goods_id']])->find();
                    $sku_info = Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();
                    $goods_order[] = [
                        'order_id' => $order_res,
                        'goods_id' => $v['goods_id'],
                        'img' => $sku_info['img'],
                        'name' => $goods_info['name'],
                        'sku_id' => $sku_info['sku_id'],
                        'price' => $sku_info['price'],
                        'count' => $v['count'],
                        'create_time' => $time
                    ];
                }
                $vice_order_res = Db::name('vice_order')->insertAll($goods_order);
                
                if ($order_res && $vice_order_res && $up_order_res) {
                    //微信支付
                    Loader::import('wxsdk\wxPay', EXTEND_PATH);
                    $obj = new \wxPay();
                    //调用示例（最后两个参数为可选参数）
                    $pay_data = $obj->jsApi($user_info['openid'], '0.01', $pay_order_sn, '商品支付', 'https://www.baidu.com/index/index/notice', '', 1);
                    
                    $return_data = array(
                        'pay_data' => $pay_data,
                        'order_id' => $order_ids
                    );
                    
                    Db::commit();
                    apiReturn(1, '获取数据成功', $return_data);
                } else {
                    Db::rollback();
                    apiReturn(2, '订单生成失败');
                }
            } else {
                Db::rollback();
                apiReturn(2, '购物车商品数据异常');
            }
        } catch (\Exception $e) {
            apiReturn(2, '系统繁忙，请稍后再试' . $e);
        }
    }
    
    /**
     * 商品确认订单
     * */
    public function confirmOrder()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $goods_id = $input['goods_id'];
        $sku_id = $input['sku_id'];
        $count = $input['count'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if (empty($count)) apiReturn(2, '商品数量异常');
        
        $sku_list = Db::name('sku_value')->field('sku_id,img,price,goods_id')->where(array('sku_id' => $sku_id, 'goods_id' => $goods_id))->select();
        if ($sku_list) {
            foreach ($sku_list as &$v) {
                $v['goods_name'] = Db::name('goods')->where(['id' => $v['goods_id']])->value('name');
                $v['img'] = getPicture($v['img']);
                $v['sku'] = implode('，', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));
                $all_price = sprintf("%.2f", $v['price'] * $count);
            }
            
            //默认收货地址
            $default_address = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(['user_id' => $user_id])->order('is_default desc,id desc')->find();
            if ($default_address) {
                $default_address['address'] = getProvinceName($default_address['province_id']) . getCityName($default_address['city_id']) . getAreaName($default_address['area_id']) . $default_address['address'];
                unset($default_address['province_id']);
                unset($default_address['city_id']);
                unset($default_address['area_id']);
            }
            
            $data = array(
                'goods_list' => $sku_list,
                'all_price' => $all_price,
                'address' => $default_address ? $default_address : []
            );
            
            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '规格不存在或已删除');
        }
    }
    
    /**
     * 立即支付【生成待支付订单】 之后 发起支付
     * */
    public function addGoodsOrder()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $goods_id = $input['goods_id'];
        $count = $input['count'];
        $sku_id = $input['sku_id'];
        $address_id = $input['address_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if ($count <= 0) apiReturn(2, '商品数量异常');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if (empty($address_id)) apiReturn(2, '请选择收货地址');
        
        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');
        
        $time = time();
        
        $goods_info = Db::name('goods')->field('id,name')->where(array('id' => $goods_id))->find();
        if ($goods_info) {
            $sku_info = Db::name('sku_value')->where(array('sku_id' => $sku_id))->find();
            if ($sku_info) {
                //商品库存
                if ($count > $sku_info['stock']) apiReturn(2, '商品库存不足');
                
                $address_info = Db::name('address')->where(array('id' => $address_id))->find();
                
                $all_price = $sku_info['price'] * $count;
                
                $order_sn = 'SN' . date('Ymd') . rand(1000, 9999) . $user_id;
                $data = array(
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'pay_order_sn' => $order_sn,
                    'all_price' => $all_price,
                    'pay_price' => $all_price,
                    'get_username' => $address_info['username'],
                    'get_mobile' => $address_info['mobile'],
                    'get_province' => getProvinceName($address_info['province_id']),
                    'get_city' => getCityName($address_info['city_id']),
                    'get_area' => getAreaName($address_info['area_id']),
                    'get_address' => $address_info['address'],
                    'create_time' => $time
                );
                
                $res = Db::name('order')->insertGetId($data);
                if ($res) {
                    $goods_order = array(
                        'order_id' => $res,
                        'goods_id' => $goods_id,
                        'img' => $sku_info['img'],
                        'name' => $goods_info['name'],
                        'sku_id' => $sku_id,
                        'price' => $sku_info['price'],
                        'count' => $count,
                        'create_time' => $time
                    );
                    Db::name('vice_order')->insert($goods_order);
                    
                    Loader::import('wxsdk\wxPay', EXTEND_PATH);
                    $obj = new \wxPay();
                    //调用示例（最后两个参数为可选参数）
                    $pay_data = $obj->jsApi($user_info['openid'], '0.01', $order_sn, '商品支付', 'https://www.baidu.com/index/index/notice', '', 1);
                    
                    $return_data = array(
                        'pay_data' => $pay_data,
                        'order_id' => $res
                    );
                    
                    apiReturn(1, '获取数据成功', $return_data);
                } else {
                    apiReturn(2, '生成订单失败');
                }
            } else {
                apiReturn(2, '规格不存在或已删除');
            }
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }
    
    /**
     * 收货地址列表
     * */
    public function addressList()
    {
        $input = Request()->param();
        $user_id = $input['user_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $list = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address,is_default')->where(['user_id' => $user_id])->order('is_default desc,create_time desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['province'] = getProvinceName($v['province_id']);
                $v['city'] = getCityName($v['city_id']);
                $v['area'] = getAreaName($v['area_id']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无收货地址', []);
        }
    }
    
    /**
     * 收货地址详情
     * */
    public function addressDetail()
    {
        $input = Request()->param();
        
        $id = $input['id'];
        
        if (empty($id)) apiReturn(2, '收货地址ID缺失');
        
        $info = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address,is_default')->where(array('id' => $id))->find();
        if ($info) {
            $info['region'] = array(getProvinceName($info['province_id']), getCityName($info['city_id']), getAreaName($info['area_id']));
            $info['defaultIndex'] = $info['is_default'] == 1 ? 0 : 1;
            
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '收货地址不存在或已删除');
        }
    }
    
    /**
     * 添加收货地址
     * */
    public function addAddress()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        $province = $input['province'];
        $city = $input['city'];
        $area = $input['area'];
        $address = $input['address'];
        $is_default = $input['is_default'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($province) || empty($city) || empty($area) || empty($address)) apiReturn(2, '请完善收货地址');
        if (empty($username)) apiReturn(2, '请填写收货人姓名');
        if (empty($mobile)) apiReturn(2, '请填写联系方式');
        
        if ($is_default == 1) {
            //查询默认的收货地址
            $default_info = Db::name('address')->where(array('user_id' => $user_id, 'is_default' => 1))->find();
        } else {
            //查询是不是第一个收货地址，是第一个收货地址的话，就设置成默认的
            $count = Db::name('address')->where(array('user_id' => $user_id))->count();
            if ($count == 0) $is_default = 1;
        }
        $data = [
            'user_id' => $user_id,
            'username' => $username,
            'mobile' => $mobile,
            'province_id' => getProvinceId($province),
            'city_id' => getCityId($province, $city),
            'area_id' => getAreaId($province, $city, $area),
            'address' => $address,
            'is_default' => $is_default,
            'create_time' => time()
        ];
        $res = Db::name('address')->insert($data);
        if ($res) {
            Db::name('address')->where(array('id' => $default_info['id']))->setField('is_default', 0);
            apiReturn(1, '添加成功');
        } else {
            apiReturn(2, '添加失败');
        }
    }
    
    /**
     * 编辑收货地址
     * */
    public function editAddress()
    {
        $input = Request()->param();
        
        $id = $input['id'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        $province = $input['province'];
        $city = $input['city'];
        $area = $input['area'];
        $address = $input['address'];
        $is_default = $input['is_default'];
        
        if (empty($id)) apiReturn(2, '收货地址ID缺失');
        if (empty($province) || empty($city) || empty($area) || empty($address)) apiReturn(2, '请完善收货地址');
        if (empty($username)) apiReturn(2, '请填写收货人姓名');
        if (empty($mobile)) apiReturn(2, '请填写联系方式');
        
        //查询默认的收货地址
        $default_info = Db::name('address')->where(['id' => $id])->find();
        $data = [
            'username' => $username,
            'mobile' => $mobile,
            'province_id' => getProvinceId($province),
            'city_id' => getCityId($province, $city),
            'area_id' => getAreaId($province, $city, $area),
            'address' => $address,
            'is_default' => $is_default,
            'update_time' => time()
        ];
        $res = Db::name('address')->where(['id' => $id])->update($data);
        if ($res) {
            if ($is_default == 1 && $default_info['is_default'] != 1) {
                //将原来的默认收货地址修改成非默认
                Db::name('address')->where(['user_id' => $default_info['user_id'], 'is_default' => 1, 'id' => ['neq', $id]])->setField('is_default', 0);
            }
            apiReturn(1, '编辑成功');
        } else {
            apiReturn(2, '编辑失败');
        }
    }
    
    /**
     * 删除收货地址
     * */
    public function delAddress()
    {
        $input = Request()->param();
        
        $id = $input['id'];
        
        if (empty($id)) apiReturn(2, '收货地址ID缺失');
        
        $info = Db::name('address')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('address')->where(['id' => $id])->delete();
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '收货地址不存在或已删除');
        }
    }
    
    /**
     * 最新消息
     * */
    public function newMsgList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        // 分页起始位置
        $offset = ($page - 1) * $pagesize;
        // 未读信息条件
        $where = '(user_id = ' . $user_id . ' or user_id = 0)';
        // 未读
        $sql = 'select id,order_id,title,content,read_user,type,create_time from ' . config('database.prefix') . 'msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
        $list = Db::name('msg')->query($sql);
        if ($list) {
            foreach ($list as &$v) {
                $v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
                $v['content'] = doEditorContent($v['content']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 分类消息列表
     * */
    public function msgList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $type = $input['type'] ?: 1;
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        // 分页起始位置
        $offset = ($page - 1) * $pagesize;
        // 未读信息条件
        $where = '(user_id = ' . $user_id . ' or user_id = 0) and type = ' . $type;
        // 未读
        $sql = 'select id,order_id,title,content,read_user,type,create_time from ' . config('database.prefix') . 'msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
        $list = Db::name('msg')->query($sql);
        if ($list) {
            foreach ($list as &$v) {
                $v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
                $v['content'] = doEditorContent($v['content']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 消息详情
     * */
    public function msgDetail()
    {
        $input = Request()->param();
        
        $id = $input['id'];
        $user_id = $input['user_id'];
        
        if (empty($id)) apiReturn(2, '消息ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $info = Db::name('msg')->field('id,title,content,read_user,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i');
            
            Db::name('msg')->where(['id' => $id])->setInc('look_count');
            
            $is_read = in_array($user_id, explode(',', $info['read_user'])) ? true : false;
            if (!$is_read) Db::name('msg')->where(['id' => $id])->setField('read_user', $info['read_user'] ? $info['read_user'] . ',' . $user_id : $user_id);
            
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '消息不存在或已删除');
        }
    }
    
    /**
     * 个人中心
     * */
    public function userCenter()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $info = Db::name('user')->field('id,avatar,username')->where(['id' => $user_id])->find();
        if ($info) {
            $info['avatar'] = doAvatar($info['avatar']);
            
            $order_where = [
                'user_id' => $user_id,
                'is_pay' => 1,
                'is_del' => 0,
                'back_order_sn' => ''
            ];
            // 待发货订单数量
            $wait_send_order_count = Db::name('order')->where($order_where)->where(['status' => 2])->count();
            // 待收货订单数量
            $wait_get_order_count = Db::name('order')->where($order_where)->where(['status' => 3])->count();
            // 待评价订单数量
            $wait_comment_order_count = Db::name('order')->where($order_where)->where(['status' => 4])->count();
            // 售后中订单数量
            $after_order_count = Db::name('order')->where($order_where)->where(['status' => 7])->count();
            // 待付款订单数量
            $order_where['is_pay'] = 0;
            $wait_pay_order_count = Db::name('order')->where($order_where)->where(['status' => 1])->count();
            
            $info['wait_pay_order_count'] = $wait_pay_order_count;
            $info['wait_send_order_count'] = $wait_send_order_count;
            $info['wait_get_order_count'] = $wait_get_order_count;
            $info['wait_comment_order_count'] = $wait_comment_order_count;
            $info['after_order_count'] = $after_order_count;
            
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '用户不存在或已禁用');
        }
    }
    
    /**
     * 我的收益详情
     * */
    public function userProfit()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        // 自己消费总额
        $me_all_consume = $this->getMeConsume($user_id);
        
        // 总累计销售额 = 我和我的所有下线的消费统计
        $all_consume = $me_all_consume + action('Algorithm/Algorithm/allConsume', ['user_id' => $user_id]);
        /**
         * 个人零售销售额 = 自己消费总额中除去自己首次消费金额
         * */
        // 自己首次消费金额
        $first_consume = Db::name('order')->where(['user_id' => $user_id, 'is_pay' => 1, 'complete_time' => ['neq', 0]])->order('id asc')->value('pay_price');
        // 个人零售销售额 = 自己消费总额 - 自己首次消费金额
        $me_consume = sprintf('%.2f', $me_all_consume - $first_consume);
        
        $profit_where = [
            'user_id' => $user_id,
            'status' => ['neq', -1],
            'type' => ['IN', [1, 2, 3]]
        ];
        // 总累计收益
        $all_profit = Db::name('profit')->where($profit_where)->sum('price');
        // 可用收益
        $normal_profit = Db::name('user')->where(['id' => $user_id])->value('all_profit');
        // 冻结收益
        $frozen_profit = Db::name('profit')->where($profit_where)->where(['status' => 1])->sum('price');
        
        $info = [
            'all_consume' => sprintf('%.2f', $all_consume),
            'me_consume' => sprintf('%.2f', $me_consume),
            'all_profit' => sprintf('%.2f', $all_profit),
            'normal_profit' => sprintf('%.2f', $normal_profit),
            'frozen_profit' => sprintf('%.2f', $frozen_profit),
        ];
        
        apiReturn(1, '获取数据成功', $info);
    }
    
    /**
     * 收益明细
     * */
    public function profitList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $status = $input['status'] ?: 0;
        $is_today = $input['is_today'] ?: 0;
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $where['user_id'] = $user_id;
        if ($status) $where['status'] = $status;
        if ($is_today) {
            $start_time = strtotime(date('Y-m-d'));
            $end_time = $start_time + 24 * 3600 - 1;
            $where['create_time'] = ['between', [$start_time, $end_time]];
        }
        
        $list = Db::name('profit')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }
    
    /**
     * 计算收益
     * */
    public function getUserProfit()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $user_info = Db::name('member')->where(['id' => $user_id])->find();
        
        if ($user_info['level'] == 1) {
            // 总收益
            $all_profit = Db::name('member')->where(['pid' => $user_id])->sum('all_profit');
            // 未结算收益
            $freeze_profit = Db::name('member')->where(['pid' => $user_id])->sum('freeze_profit');
            // 已结算收益
            $settle_profit = $all_profit - $freeze_profit;
            // 今日收益
            $today_profit = Db::name('member')->where(['pid' => $user_id])->sum('today_profit');
        } else {
            // 总收益
            $all_profit = $user_info['all_profit'];
            // 未结算收益
            $freeze_profit = $user_info['freeze_profit'];
            // 已结算收益
            $settle_profit = $all_profit - $freeze_profit;
            // 今日收益
            $today_profit = $user_info['today_profit'];
        }
        
        $data = [
            'all_profit' => sprintf('%.2f', $all_profit),
            'freeze_profit' => sprintf('%.2f', $freeze_profit),
            'settle_profit' => sprintf('%.2f', $settle_profit),
            'today_profit' => sprintf('%.2f', $today_profit)
        ];
        
        apiReturn(1, '获取数据成功', $data);
    }
    
    /**
     * 提现记录
     * */
    public function withdrawalList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $list = Db::name('withdrawal')->field('id,real_price price,type,status,create_time')->where(['user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['desc'] = $v['status'] == 1 ? '提现到' . ($v['type'] == 1 ? '微信钱包' : '银行卡') : '提现审核失败';
                $v['change'] = $v['status'] == 1 ? 'plus' : 'minus';
                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 提现页面数据回显
     * */
    public function withdrawalInfo()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $user_info = Db::name('user')->field('id,all_profit,real_name,bank_name,bank_num,bank_deposit')->where(['id' => $user_id])->find();
        
        $empty_bank = ['请选择'];
        $bank_list = C('BANK_LIST');
        $bank_list = array_merge($empty_bank, $bank_list);
        $bankIndex = 0;
        if ($bank_list) {
            foreach ($bank_list as $k => &$v) {
                if ($user_info['bank_name'] == $v) {
                    $bankIndex = $k;
                    break;
                }
            }
        }
        
        $withdrawal_price = C('WITHDRAWAL_PRICE');
        
        $service_rate = C('SERVICE_RATE');
        
        $data = [
            'user_info' => $user_info,
            'bank_list' => $bank_list,
            'bankIndex' => $bankIndex,
            'withdrawal_price' => $withdrawal_price,
            'service_rate' => $service_rate
        ];
        
        apiReturn(1, '获取数据成功', $data);
    }
    
    /**
     * 申请提现
     * */
    public function applyWithdrawal()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $price = $input['price'];
        $service_rate = $input['service_rate'];
        $real_price = $input['real_price'];
        $real_name = $input['real_name'];
        $bank_name = $input['bank_name'];
        $bank_num = $input['bank_num'];
        $bank_deposit = $input['bank_deposit'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($price)) apiReturn(2, '请输入提现金额');
        if (empty($real_price)) apiReturn(2, '实际到账金额错误');
        
        $time = time();
        
        $withdrawal_price = C('WITHDRAWAL_PRICE');
        
        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d')) + 24 * 3600 - 1;
        $count = Db::name('withdrawal')->where(['user_id' => $user_id, 'status' => ['neq', 2], 'create_time' => ['between', [$start_time, $end_time]]])->count();
        if ($count) apiReturn(2, '每号每天限提一次');
        
        Db::startTrans();
        try {
            $user_info = Db::name('user')->where(['id' => $user_id])->find();
            
            $order_sn = uniqid();                //订单号
            
            if ($price <= $withdrawal_price) {
                if (empty($user_info['openid'])) apiReturn(2, 'openid缺失');
                
                // 提现到微信零钱
                $mchid = C('MCH_ID');          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
                $appid = C('XCX_APPID');       //微信支付申请对应的公众号的APPID
                $appKey = C('XCX_SECRET');     //微信支付申请对应的公众号的APP Key
                $apiKey = C('MCH_KEY');        //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥
                
                Loader::import('weixinPay\weixinPay-master\transfers', EXTEND_PATH);
                $obj = new \WxpayService($mchid, $appid, $appKey, $apiKey);
                
                $obj->createJsBizPackage($user_info['openid'], $price, $order_sn, $real_name);
                
                $data = [
                    'order_sn' => $order_sn,
                    'user_id' => $user_id,
                    'price' => $price,
                    'type' => 1,
                    'create_time' => $time
                ];
                Db::name('withdrawal')->insert($data);
            } else {
                if (empty($real_name) || $real_name == 'undefined') apiReturn(2, '姓名信息异常，请重新输入');
                if (empty($bank_name) || $bank_name == 'undefined' || $bank_name == '请选择') apiReturn(2, '请选择银行');
                if (empty($bank_num) || $bank_num == 'undefined') apiReturn(2, '银行卡号信息异常，请重新输入');
                if (empty($bank_deposit) || $bank_deposit == 'undefined') apiReturn(2, '开户行信息异常，请重新输入');
                
                // 申请提现到银行卡
                $data = [
                    'order_sn' => $order_sn,
                    'user_id' => $user_id,
                    'price' => $price,
                    'rate' => $service_rate,
                    'service_price' => $price - $real_price,
                    'real_price' => $real_price,
                    'type' => 2,
                    'real_name' => $real_name,
                    'bank_name' => $bank_name,
                    'bank_num' => $bank_num,
                    'bank_deposit' => $bank_deposit,
                    'create_time' => $time
                ];
                Db::name('withdrawal')->insert($data);
            }
            
            $user_data = [
                'all_profit' => $user_info['all_profit'] - $price,
                'real_name' => $real_name,
                'bank_name' => $bank_name,
                'bank_num' => $bank_num,
                'bank_deposit' => $bank_deposit
            ];
            Db::name('user')->where(['id' => $user_id])->update($user_data);
            
            Db::commit();
            apiReturn(1, '申请提现成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~' . $e);
        }
    }
    
    /**
     * 订单列表
     * */
    public function orderList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $status = $input['status'] ?: 0;
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;
        $list = Db::name('order')->field('id,order_sn,pay_price,status')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['status_desc'] = doOrderStatus($v['status']);
                
                $goods_list = Db::name('vice_order')->field('id,img,name,price,count,sku_id')->where(['order_id' => $v['id']])->select();
                if ($goods_list) {
                    foreach ($goods_list as &$val) {
                        $val['img'] = getPicture($val['img']);
                        if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                    }
                    $v['goods_list'] = $goods_list;
                }
            }
            
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 订单详情
     * */
    public function orderDetail()
    {
        $input = Request()->param();
        
        $id = $input['id'];
        
        if (empty($id)) apiReturn(2, '订单ID缺失');
        
        $info = Db::name('order')->field('id,order_sn,all_price,freight_price,coupon_id,remark,pay_price,status,pay_type,express_id,send_num,get_username,get_mobile,get_province,get_city,get_area,get_address,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i:s');
            $info['status_desc'] = doOrderStatus($info['status']);
            
            $coupon_price = 0;
            if ($coupon_id = $info['coupon_id']) $coupon_price = Db::name('user_coupon')->where(['id' => $coupon_id])->value('face_price');
            $info['coupon_price'] = sprintf('%.2f', $coupon_price);
            
            if ($express_id = $info['express_id']) $info['express_name'] = Db::name('express')->where(['id' => $express_id])->value('name');
            
            $goods_list = Db::name('vice_order')->field('id,goods_id,img,name,price,count,sku_id,gift_ids')->where(['order_id' => $id])->select();
            if ($goods_list) {
                foreach ($goods_list as &$val) {
                    $val['img'] = getPicture($val['img']);
                    if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                    
                    $gift_list = [];
                    if ($val['gift_ids']) $gift_list = Db::name('goods_gift')->field('id,gift_img,gift_name,gift_price')->where(['id' => ['IN', $val['gift_ids']], 'is_del' => 0, 'start_date' => ['elt', date('Y-m-d')], 'end_date' => ['egt', date('Y-m-d')]])->select();
                    if ($gift_list) {
                        foreach ($gift_list as &$value) {
                            $value['gift_img'] = getPicture($value['gift_img']);
                        }
                    }
                    $val['gift_list'] = $gift_list;
                }
                
                $info['goods_list'] = $goods_list;
            }
            
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }
    
    /**
     * 信息设置回显数据
     * */
    public function userInfo()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $user_info = Db::name('user')->field('id,avatar,username,gender,mobile')->where(['id' => $user_id])->find();
        if ($user_info) {
            $user_info['avatar_path'] = doAvatar($user_info['avatar']);
            $user_info['hide_mobile'] = hideMobile($user_info['mobile']);
            
            $address_info = Db::name('address')->field('province_id,city_id,area_id')->where(['user_id' => $user_id])->order('is_default desc')->find();
            if ($address_info) {
                $address = getProvinceName($address_info['province_id']) . getCityName($address_info['city_id']) . getAreaName($address_info['area_id']);
                $user_info['address'] = $address;
            } else {
                $user_info['address'] = '';
            }
            
            apiReturn(1, '获取数据成功', $user_info);
        } else {
            apiReturn(2, '用户信息不存在或已禁用');
        }
    }
    
    /**
     * 保存用户信息
     * */
    public function saveUserInfo()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $avatar = $input['avatar'];
        $username = $input['username'];
        $gender = $input['gender'];
        $mobile = $input['mobile'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($avatar)) apiReturn(2, '请上传头像');
        if (empty($username)) apiReturn(2, '请输入昵称');
        
        $info = Db::name('user')->where(['id' => $user_id])->find();
        
        if ($info) {
            $data = [
                'avatar' => $avatar,
                'username' => $username,
                'gender' => $gender,
                'mobile' => $mobile,
                'update_time' => time()
            ];
            
            $res = Db::name('user')->where(['id' => $user_id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功');
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            apiReturn(2, '用户不存在或已删除');
        }
    }
    
    /**
     * 我的券包
     * */
    public function couponList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $status = $input['status'] ?: 0;
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;
        
        $list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price,expire_time,status,create_time')->where($where)->order('status asc,expire_time asc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['expire_time'] = str_replace('-', '.', $v['expire_time']);
                $v['desc'] = '限' . timeFormat($v['create_time'], 'Y.m.d') . '-' . $v['expire_time'] . '期间使用';
            }
            
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 我的收藏
     * */
    public function collectList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        $list = Db::name('collect c')
            ->join('xindu_goods g', 'c.to_id = g.id', 'left')
            ->field('g.id,g.img,g.name,g.min_price,g.min_vip_price')
            ->where(['user_id' => $user_id, 'type' => 1, 'status' => 1])
            ->page($page, $pagesize)
            ->select();
        
        if ($list) {
            $user_level = Db::name('user')->where(['id' => $user_id])->value('level');
            
            foreach ($list as &$v) {
                $price = $user_level > 1 ? $v['min_vip_price'] : $v['min_price'];
                $v['price'] = sprintf('%.2f', $price);
                $v['img'] = getPicture($v['img']);
            }
            
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }
    
    /**
     * 我的分享
     * */
    public function getShareData()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        
        //分享二维码
        $qr = Db::name('user')->where(['id' => $user_id])->value('qr');
        if (!$qr) {
            $qr = createUserQr($user_id);
        }
        $qr = getPicture($qr);
        
        // 顾客总数：形成上下级关系
        $bind_user_count = Db::name('user')->where(['up_user_id' => $user_id])->count();
        
        // 成功分享：已激活的总数
        $success_user_count = Db::name('user')->where(['up_user_id' => $user_id])->count();
        
        // 今日新增
        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d')) + 24 * 3600 - 1;
        $today_bind_user_count = Db::name('user')->where(['up_user_id' => $user_id, 'create_time' => ['between', [$start_time, $end_time]]])->count();
        
        $data = [
            'qr' => $qr,
            'bind_user_count' => $bind_user_count,
            'success_user_count' => $success_user_count,
            'today_bind_user_count' => $today_bind_user_count,
        ];
        
        apiReturn(1, '获取数据成功', $data);
    }
    
    /**
     * 意见反馈
     * */
    public function addFeedback()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $content = $input['content'];
        
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($content)) apiReturn(2, '请输入反馈意见');
        
        checkContent($content);
        
        $data = [
            'user_id' => $user_id,
            'content' => $content,
            'create_time' => time()
        ];
        
        $res = Db::name('feedback')->insert($data);
        if ($res) {
            apiReturn(1, '反馈成功');
        } else {
            apiReturn(2, '反馈失败');
        }
    }
    
    /**
     * 关于我们
     * */
    public function aboutUs()
    {
        $content = Db::name('about_us')->where(['id' => 1])->value('content');
        
        $content = doEditorContent($content);
        
        apiReturn(1, '获取数据成功', $content);
    }
    
    /**
     * 登录
     * */
    public function login()
    {
        $input = Request()->param();
        
        $openid = $input['openid'];
        $share_user_id = $input['share_user_id'] ?: 0;
        
        if (empty($openid)) apiReturn(2, 'openid缺失');
//        if (empty($share_user_id)) apiReturn(2, '上级分享用户ID缺失');
        
        $user_info = Db::name('member')->where(['openid' => $openid])->find();
        if ($user_info) {
            $data = [
                'user_id' => $user_info['id'],
                'avatar' => doAvatar($user_info['avatar']),
                'username' => $user_info['username']
            ];
            apiReturn(1, '登录成功', $data);
        } else {
            $data = [
                'avatar' => 0,
                'username' => '微信用户',
                'openid' => $openid,
                'pid' => $share_user_id,
//                'examine' => 1,
                'create_time' => time()
            ];
            
            if ($share_user_id) {
                $share_user_info = Db::name('member')->where(['id' => $share_user_id])->find();
                if ($share_user_info['is_del'] || $share_user_info['status'] == 2) apiReturn(2, '登录失败，上级分享用户已删除或已禁用，请重新扫码');
                if ($share_user_info['level'] >= 4) apiReturn(2, '登录失败，该二维码所属用户等级异常');
                
                $share_level = $share_user_info['level'];
                
                $data['level'] = $share_level + 1;
            } else {
                $data['level'] = 4;
            }
            
            $user_id = Db::name('member')->insertGetId($data);
            if ($user_id) {
                $qr = createUserQr($user_id);
                if ($qr) Db::name('member')->where(['id' => $user_id])->setField('qr', $qr);
                
                $user_data = [
                    'avatar' => 0,
                    'username' => '微信用户',
                    'user_id' => $user_id,
                    'level' => $data['level'],
                    'level_desc' => doUserLevel($data['level'])
                ];
                apiReturn(1, '登录成功', $user_data);
            } else {
                apiReturn(2, '登录失败');
            }
        }
    }
    
    /**
     * 申请招商经理
     * */
    public function applyOneUser()
    {
        $input = Request()->param();
        
        $openid = $input['openid'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        
        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($username)) apiReturn(2, '请输入姓名');
        if (empty($mobile)) apiReturn(2, '请输入手机号');
        
        $where['openid'] = ['neq', $openid];
        $where['mobile'] = $mobile;
        $mobile_count = Db::name('member')->where($where)->count();
        if ($mobile_count) apiReturn(2, '手机号已存在');
        
        $count = Db::name('member')->where(['openid' => $openid])->count();
        
        $time = time();
        $data = [
            'username' => $username,
            'mobile' => $mobile,
            'level' => 1,
            'examine' => 0
        ];
        
        if ($count) {
            $data['update_time'] = $time;
            
            $res = Db::name('member')->where(['openid' => $openid])->update($data);
        } else {
            $data['create_time'] = $time;
            
            $res = Db::name('member')->insert($data);
        }
        
        if ($res) {
            apiReturn(1, '提交成功');
        } else {
            apiReturn(2, '提交失败');
        }
    }
    
    /**
     * 获取用户信息
     * */
    public function getUserInfo()
    {
        $input = Request()->param();
        
        $openid = $input['openid'];
        
        if (empty($openid)) apiReturn(2, 'openid缺失');
        
        $info = Db::name('member')->field('id,avatar,username,mobile,level,examine,qr,all_profit,freeze_profit,today_profit,profit')->where(['openid' => $openid])->find();
        if ($info) {
            $info['qr'] = getPicture($info['qr']);
            $info['avatar_path'] = doAvatar($info['avatar']);
            $info['level_desc'] = doLevel($info['level'], $info['examine']);
            
            $start_time = strtotime(date('Y-m-d'));
            $end_time = strtotime(date('Y-m-d 23:59:59'));
            $today_new_user_count = Db::name('member')->where(['is_del' => 0, 'create_time' => ['between', [$start_time, $end_time]], 'pid' => $info['id']])->count();
            $all_user_count = Db::name('member')->where(['is_del' => 0, 'pid' => $info['id']])->count();
            
            $info['today_new_user_count'] = $today_new_user_count;
            $info['all_user_count'] = $all_user_count;
    
            $all_profit = 0;
            $freeze_profit = 0;
            $settle_profit = 0;
            $today_profit = 0;
            // 计算佣金
            if ($info['level'] == 1) {
                $son_ids = getSonIds($info['id']);
                if($son_ids){
                    // 总收益
                    $all_profit = Db::name('member')->where(['id' => ['IN', $son_ids]])->sum('all_profit');
                    // 未结算收益
                    $freeze_profit = Db::name('member')->where(['id' => ['IN', $son_ids]])->sum('freeze_profit');
                    // 已结算收益
                    $settle_profit = $all_profit - $freeze_profit;
                    // 今日收益
                    $today_profit = Db::name('member')->where(['id' => ['IN', $son_ids]])->sum('today_profit');
                }
            } else {
                // 总收益
                $all_profit = $info['all_profit'];
                // 未结算收益
                $freeze_profit = $info['freeze_profit'];
                // 已结算收益
                $settle_profit = $all_profit - $freeze_profit;
                // 今日收益
                $today_profit = $info['today_profit'];
            }
            
            $info['all_profit'] = sprintf('%.2f', $all_profit);
            $info['freeze_profit'] = sprintf('%.2f', $freeze_profit);
            $info['settle_profit'] = sprintf('%.2f', $settle_profit);
            $info['today_profit'] = sprintf('%.2f', $today_profit);
            
            // apply_status：1：可以申请，2：申请中，3：不可申请
            if ($info['level'] == 4) {
                if ($info['examine'] == -1 || $info['examine'] == 2) {
                    $info['apply_status'] = 1;
                } elseif ($info['examine'] == 0) {
                    $info['apply_status'] = 2;
                } else {
                    $info['apply_status'] = 3;
                }
            } else {
                $info['apply_status'] = 3;
            }
            
            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '获取数据失败');
        }
    }
    
    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();
        
        $openid = $input['openid'];
        $code = $input['code'];
        
        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');
        
        $token = get_access_token('xcx_access_token.json', 2);
        if (empty($token)) apiReturn(2, 'TOKEN缺失');
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;
        
        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        $result = json_decode($result, true);
        
        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];
            
            if ($mobile) {
                $count = Db::name('member')->where(['mobile' => $mobile, 'openid' => ['neq', $openid]])->count();
                if ($count > 0) apiReturn(2, '手机号码已存在');
                
                apiReturn(1, '获取数据成功', $mobile);
            } else {
                file_put_contents(RUNTIME_PATH . 'mobileErrGetMobile.txt', '手机号不存在===>' . json_encode($result, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            file_put_contents(RUNTIME_PATH . 'ApiErrGetMobile.txt', '时间：' . date('Y-m-d H:i:s') . '，用户openid：' . $openid . ' ===> 错误码：' . $result['errcode'] . '；错误信息：' . $result['errmsg'] . '；code：' . $code . PHP_EOL, FILE_APPEND);
            if ($result['errcode'] == 40001) {
                unlink(RUNTIME_PATH . '/xcx_access_token.json');
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }
    
    /**
     * 检测是否存在手机号
     * */
    public function checkUserMobile()
    {
        $input = Request()->param();
        
        $openid = $input['openid'];
        
        if (empty($openid)) apiReturn(2, 'OPENID缺失');
        
        $mobile = Db::name('member')->where(['openid' => $openid])->value('mobile');
        
        apiReturn(1, '获取数据成功', (bool)$mobile);
    }
    
    /**
     * 修改信息
     * */
    public function setUserInfo()
    {
        $input = Request()->param();
        
        $openid = $input['openid'];
        $avatar = $input['avatar'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        $share_user_id = $input['share_user_id'] ?: 0;
        
        if (empty($openid)) apiReturn(2, 'openid缺失');
        if (empty($avatar)) apiReturn(2, '请上传头像');
        if (empty($username)) apiReturn(2, '请输入姓名');
        if (empty($mobile)) apiReturn(2, '请绑定手机号');
        
        $where['openid'] = ['neq', $openid];
        $where['mobile'] = $mobile;
        $mobile_count = Db::name('member')->where($where)->count();
        if ($mobile_count) apiReturn(2, '手机号已存在');
        
        $time = time();
        $data = [
            'avatar' => $avatar,
            'username' => $username,
            'mobile' => $mobile
        ];
        
        $share_user_info = Db::name('member')->where(['id' => $share_user_id])->find();
        
        $info = Db::name('member')->where(['openid' => $openid])->find();
        if ($info) {
            if ($share_user_info && !$info['pid']) {
                $data['pid'] = $share_user_id;
                $data['level'] = $share_user_info['level'] + 1;
            }
            
            $data['update_time'] = $time;
            
            $res = Db::name('member')->where(['openid' => $openid])->update($data);
            $user_id = $info['id'];
        } else {
            if ($share_user_info) {
                $data['pid'] = $share_user_id;
                $data['level'] = $share_user_info['level'] + 1;
            }
            $data['openid'] = $openid;
            $data['create_time'] = $time;
            
            $res = Db::name('member')->insertGetId($data);
            $user_id = $res;
        }
        
        if ($res) {
            $return_data = [
                'user_id' => $user_id,
                'avatar_path' => doAvatar($avatar),
                'username' => $username,
                'level_desc' => doLevel($info['level'] ?: $data['level'], $info['examine'])
            ];
            
            apiReturn(1, '保存成功', $return_data);
        } else {
            apiReturn(2, '保存失败');
        }
    }
    
    /**
     * 绑定上下级关系（普通用户除外）
     * */
    public function bindUser()
    {
        $input = Request()->param();
        
        $openid = $input['openid'];
        $share_user_openid = $input['share_user_openid'] ?: '';
        if ($share_user_openid) {
            $info = Db::name('member')->where(['openid' => $share_user_openid])->find();
            if ($info['is_del'] == 0 && $info['status'] == 1 && $info['level'] < 4) {
                // 分享人数据正常
                $user_info = Db::name('member')->where(['openid' => $openid])->find();
                if (!$user_info['pid'] && $user_info['level'] == 4) {
                    $data = [
                        'pid' => $info['id'],
                        'level' => $info['level'] + 1
                    ];
                    
                    Db::name('member')->where(['openid' => $openid])->update($data);
                }
            }
        }
    }
    
    /**
     * 获取客户数量
     * */
    public function getMemberCount()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $is_today = $input['is_today'] ?: 0;
        
        $where['pid'] = $user_id;
        $where['is_del'] = 0;
        if ($is_today) {
            $start_time = strtotime(date('Y-m-d'));
            $end_time = strtotime(date('Y-m-d 23:59:59'));
            
            $where['create_time'] = ['between', [$start_time, $end_time]];
        }
        $count = Db::name('member')->where($where)->count();
        
        apiReturn(1, '获取数据成功', $count ?: 0);
    }
    
    /**
     * 客户列表
     * */
    public function getMemberList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $is_today = $input['is_today'] ?: 0;
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '用户ID缺失');
        
        $where['pid'] = $user_id;
        $where['is_del'] = 0;
        if ($is_today) {
            $start_time = strtotime(date('Y-m-d'));
            $end_time = strtotime(date('Y-m-d 23:59:59'));
            
            $where['create_time'] = ['between', [$start_time, $end_time]];
        }
        
        $list = Db::name('member')->where($where)->order('create_time asc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = doAvatar($v['avatar']);
                $v['level_desc'] = doLevel($v['level'], $v['examine']);
                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }
    
    /**
     * 推广视频列表
     * */
    public function feedList()
    {
        $list = Db::name('feed')->order('sort asc,create_time desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['sph_id'] = C('SPH_ID');
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }
    
    /**
     * 申请提现
     * */
    public function applyWithdraw()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $profit = $input['profit'];
        
        if (empty($user_id)) apiReturn(2, '用户ID缺失');
        if (empty($profit)) apiReturn(2, '请输入提现金额');
        
        $user_info = Db::name('member')->where(['id' => $user_id, 'is_del' => 0])->find();
        if (empty($user_info)) apiReturn(2, '用户不存在或已删除');
        if ($user_info['status'] == 2) apiReturn(2, '账号已禁用');
        if ($user_info['profit'] < $profit) apiReturn(2, '申请提现金额过大');
        
        Db::startTrans();
        try {
            $time = time();
            
            $data = [
                'user_id' => $user_id,
                'profit' => $profit,
                'create_time' => $time
            ];
            Db::name('withdraw')->insert($data);
            
            Db::name('member')->where(['id' => $user_id])->setField('profit', $user_info['profit'] - $profit);
            
            Db::commit();
            
            apiReturn(1, '申请提现成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '申请提现失败');
        }
    }
    
    /**
     * 提现记录
     * */
    public function withdrawList()
    {
        $input = Request()->param();
        
        $user_id = $input['user_id'];
        $status = $input['status'];
        $page = $input['page'] ?: 1;
        $pagesize = $input['pagesize'] ?: 10;
        
        if (empty($user_id)) apiReturn(2, '用户ID缺失');
        
        $where['user_id'] = $user_id;
        if ($status == 1) {
            $where['status'] = 1;
        } elseif ($status == 2) {
            $where['status'] = ['IN', [2, 3]];
        }
        
        $list = Db::name('withdraw')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time']);
                switch ($v['status']) {
                case 1:
                    $status_desc = '审核中';
                    break;
                case 2:
                    $status_desc = '提现成功';
                    break;
                case 3:
                    $status_desc = '提现失败';
                    break;
                }
                $v['status_desc'] = $status_desc;
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }
    
    /**
     * 商城小程序支付订单回调分佣程序
     * */
    public function doShopOrderNotice()
    {
        $input = Request()->param();
        
        $mobile = $input['mobile'];
        $order_sn = $input['order_sn'];
        $order_price = $input['order_price'];
        
        $time = time();
        Db::startTrans();
        try {
            $user_info = Db::name('member')->where(['mobile' => $mobile])->find();
            if ($user_info && $pid = $user_info['pid']) {
                if ($pid) {
                    $rate_info = Db::name('rate_config')->where(['id' => 1])->find();
                    if ($rate_info) {
                        $profit_data = [];
                        
                        $parent_user_info = Db::name('member')->where(['id' => $pid])->find();
                        if ($parent_user_info) {
                            // 分享官分佣
                            if ($parent_user_info['level'] == 3) {
                                if ($three_rate = $rate_info['three_rate']) {
                                    $profit = $order_price * $three_rate / 100;
                                    // 分享官
                                    $three_member_data = [
                                        'all_profit' => $parent_user_info['all_profit'] + $profit,
                                        'freeze_profit' => $parent_user_info['freeze_profit'] + $profit,
                                        'today_profit' => $parent_user_info['today_profit'] + $profit
                                    ];
                                    Db::name('member')->where(['id' => $parent_user_info['id']])->update($three_member_data);
                                    
                                    $profit_data[] = [
                                        'user_id' => $parent_user_info['id'],
                                        'order_sn' => $order_sn,
                                        'order_price' => $order_price,
                                        'profit' => $profit,
                                        'create_time' => $time
                                    ];
                                }
                                
                                // 城市合伙人分佣
                                if ($parent_user_info['pid']) {
                                    $two_user_info = Db::name('member')->where(['id' => $parent_user_info['pid']])->find();
                                    if ($two_user_info) {
                                        if ($two_user_info['level'] == 2) {
                                            if ($two_rate = $rate_info['two_rate']) {
                                                $profit = $order_price * $two_rate / 100;
                                                $two_member_data = [
                                                    'all_profit' => $two_user_info['all_profit'] + $profit,
                                                    'freeze_profit' => $two_user_info['freeze_profit'] + $profit,
                                                    'today_profit' => $two_user_info['today_profit'] + $profit
                                                ];
                                                Db::name('member')->where(['id' => $two_user_info['id']])->update($two_member_data);
                                                
                                                $profit_data[] = [
                                                    'user_id' => $two_user_info['id'],
                                                    'order_sn' => $order_sn,
                                                    'order_price' => $order_price,
                                                    'profit' => $profit,
                                                    'create_time' => $time
                                                ];
                                            }
                                        }
                                    }
                                }
                            }
                            
                            // 城市合伙人
                            if ($parent_user_info['level'] == 2) {
                                if ($two_rate = $rate_info['two_rate']) {
                                    $profit = $order_price * $two_rate / 100;
                                    $two_member_data = [
                                        'all_profit' => $parent_user_info['all_profit'] + $profit,
                                        'freeze_profit' => $parent_user_info['freeze_profit'] + $profit,
                                        'today_profit' => $parent_user_info['today_profit'] + $profit
                                    ];
                                    Db::name('member')->where(['id' => $parent_user_info['id']])->update($two_member_data);
                                    
                                    $profit_data[] = [
                                        'user_id' => $parent_user_info['id'],
                                        'order_sn' => $order_sn,
                                        'order_price' => $order_price,
                                        'profit' => $profit,
                                        'create_time' => $time
                                    ];
                                }
                            }
                        }
                    }
                    
                    if ($profit_data) Db::name('profit')->insertAll($profit_data);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }
    
    /**
     * 佣金解冻
     * */
    public function thawProfit()
    {
        $input = Request()->param();
        
        $order_sn = $input['order_sn'];
        
        if ($order_sn) {
            Db::startTrans();
            try {
                $profit_list = Db::name('profit')->where(['order_sn' => $order_sn])->select();
                if ($profit_list) {
                    foreach ($profit_list as &$v) {
                        if($v['status'] == 1){
                            Db::name('profit')->where(['id' => $v['id']])->setField('status', 2);
    
                            $profit = $v['profit'];
    
                            $info = Db::name('member')->where(['id' => $v['user_id']])->find();
                            $data = [
                                'freeze_profit' => $info['freeze_profit'] - $profit,
                                'profit' => $info['profit'] + $profit
                            ];
                            Db::name('member')->where(['id' => $v['user_id']])->update($data);
                        }
                    }
                    Db::commit();
                }
            } catch (\Exception $e) {
                Db::rollback();
            }
        }
    }
}
